package me.jessyan.mvparms.demo.mvp.ui.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * The author: Zhao X.H.
 * Creation time: 2018/6/7 ${time}
 */

public class WrapContentHeightViewPager extends ViewPager {
    private Context mContext;
    private int viewHeight;
    public WrapContentHeightViewPager(Context context) {
        super(context);
        this.mContext = context;
    }

    public WrapContentHeightViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
    }

    private int height = 0;
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        for (int i = 0; i < getChildCount(); i++) {
//            View child = getChildAt(i);
//            child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
//            int h = child.getMeasuredHeight();
//            if (h > height) height = h;
//        }
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
        View childView = getChildAt(current);
        if (childView != null)  //有可能没有子view
        {
            childView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            viewHeight = childView.getMeasuredHeight();   //得到父元素对自身设定的高
            // UNSPECIFIED(未指定),父元素部队自元素施加任何束缚，子元素可以得到任意想要的大小
            //EXACTLY(完全)，父元素决定自元素的确切大小，子元素将被限定在给定的边界里而忽略它本身大小；
            //AT_MOST(至多)，子元素至多达到指定大小的值。
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(viewHeight, MeasureSpec.EXACTLY);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    private int current;
    private HashMap<Integer, View> mChildrenViews = new LinkedHashMap<Integer, View>();
    public void resetHeight(int current) {
        this.current = current;
        if (getChildCount() > current) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams();
            if (layoutParams == null) {
                layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, viewHeight);
            } else {
                layoutParams.height = viewHeight;
            }
            setLayoutParams(layoutParams);
        }
    }



    /**
     * 保存View对应的索引,需要自适应高度的一定要设置这个
     */
    public void setViewForPosition(View view, int position) {
        mChildrenViews.put(position, view);
    }



    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        try {
            Field mFirstLayout = ViewPager.class.getDeclaredField("mFirstLayout");
            mFirstLayout.setAccessible(true);
            mFirstLayout.set(this, false);
            getAdapter().notifyDataSetChanged();
            setCurrentItem(getCurrentItem());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean hasActivityDestroy;
    @Override
    protected void onDetachedFromWindow() {
        if (hasActivityDestroy) {
            super.onDetachedFromWindow();
        }
    }

    public void setHasDestroy(boolean hasDestroy) {
        hasActivityDestroy= hasDestroy;
    }

    /**
     *这个方法是通过反射，修改viewpager的触发切换的最小滑动速度（还是距离？姑
     * 且是速度吧！滑了10dp就给它切换）
     **/


    /****
     * 滑动距离及坐标 归还父控件焦点
     ****/
    private float xDistance, yDistance, xLast, yLast;
    /**
     * 是否是左右滑动
     **/
    private boolean mIsBeingDragged = true;

//    /**
//     *重写这个方法纯属是为了告诉Recyclerview，什么时候不要拦截viewpager的滑动
//     *事件
//     **/
//    @Override
//    public boolean dispatchTouchEvent(MotionEvent ev) {
//        getParent().requestDisallowInterceptTouchEvent(true);
//        switch (ev.getAction()) {
//            case MotionEvent.ACTION_DOWN:
//                xDistance = yDistance = 0f;
//                xLast = ev.getX();
//                yLast = ev.getY();
//                break;
//            case MotionEvent.ACTION_MOVE:
//                final float curX = ev.getX();
//                final float curY = ev.getY();
//                xDistance += Math.abs(curX - xLast);
//                yDistance += Math.abs(curY - yLast);
//                xLast = curX;
//                yLast = curY;
//                if (!mIsBeingDragged) {
//                    if (yDistance < xDistance * 0.5) {//小于30度都左右滑
//                        mIsBeingDragged = true;
//                        getParent().requestDisallowInterceptTouchEvent(true);
//                    } else {
//                        mIsBeingDragged = false;
//                        getParent().requestDisallowInterceptTouchEvent(false);
//                    }
//                }
//                break;
//            case MotionEvent.ACTION_UP:
//            case MotionEvent.ACTION_CANCEL:
//                mIsBeingDragged = false;
//                break;
//        }
//        return super.dispatchTouchEvent(ev);
//    }


}
